package com.os.controller;

import cn.hutool.core.util.ObjectUtil;
import com.os.domain.MetaData;
import com.os.exception.Asserts;
import com.os.model.MetaDataInfo;
import com.os.result.Resp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.os.service.MetaDataService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 风亦未止
 * @date 2023/5/3 17:03
 */
@RestController
@RequestMapping("/metaServer")
public class MetaDataController {
    @Autowired
    private MetaDataService metaDataService;

    @PutMapping("/")
    public Resp put(@RequestBody MetaDataInfo metaDataInfo) {
        if(ObjectUtil.isNull(metaDataInfo)){
            Asserts.fail("元数据对象为null~");
        }
        MetaData metaData = new MetaData();
        BeanUtils.copyProperties(metaDataInfo, metaData);
        MetaData save = metaDataService.save(metaData);
        if(ObjectUtil.isNull(save)){
            return Resp.failed();
        }
        return Resp.success(save,"添加成功！");
    }

    @GetMapping("/{name}")
    public Resp<MetaDataInfo> get(@PathVariable("name")String name){
        MetaData metaData = metaDataService.findLatestByName(name);
        if(ObjectUtil.isNotNull(metaData)){
            MetaDataInfo metaDataInfo = new MetaDataInfo();
            BeanUtils.copyProperties(metaData, metaDataInfo);
            return Resp.success(metaDataInfo, "成功获取对象最新版本");
        }
        return Resp.success(null, "该对象未上传~");
    }


    @GetMapping("/{name}/{version}")
    public Resp<MetaDataInfo> getByVersion(@PathVariable("name")String name,
                             @PathVariable("version") Integer version){
        MetaData metaData = metaDataService.findByNameAndVersion(name, version);
        if(ObjectUtil.isNotNull(metaData)){
            MetaDataInfo metaDataInfo = new MetaDataInfo();
            BeanUtils.copyProperties(metaData, metaDataInfo);
            return Resp.success(metaDataInfo, "成功获取对应版本对象");
        }
        return Resp.success(null, "该对象未上传~");
    }

    @GetMapping("/version/{name}")
    public Resp<List<MetaDataInfo>> getAllVersion(@PathVariable("name")String name){
        List<MetaData> metaDataList = metaDataService.findByName(name);
        if(metaDataList != null && metaDataList.size() != 0){
            List<MetaDataInfo> res = new ArrayList<>();
            metaDataList.stream().forEach((metaData -> {
                MetaDataInfo metaDataInfo = new MetaDataInfo();
                BeanUtils.copyProperties(metaData, metaDataInfo);
                res.add(metaDataInfo);
            }));
            return Resp.success(res, "成功获取该对象所有版本信息~");
        }
        return Resp.success(null, "该对象未上传~");
    }


}
